package com.tools;

import java.awt.Frame;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

public class CompressImage {
	protected ImageWriter imgWrier;
	protected ImageWriteParam imgWriteParams;

	private int width = 270;
	private int height = 200;
	private float quality = 0.5f;// //这个值范围为0-1.0,值越小，压缩的越小，当然图片失真越明显
	private static CompressImage compress;

	private CompressImage() {

	}

	public static CompressImage getImageCompress() {
		if (null == compress) {
			compress = new CompressImage();
		}
		return compress;
	}

//	public static void main(String arg[]){
//		for(int i= 0;i <600;i++){
//			try {
//				Files.copyFile("C:\\workspace\\tom\\res\\img\\android.jpg","C:\\workspace\\tom\\res\\img\\"+i+".jpg");
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}
	public void compress(File src, File des) {
		try {
			// 压缩前的JPEG文件

			// 压缩前后的JPEG文件
			if (!des.exists()) {
				des.createNewFile();
			}

			// 压缩百分比
			if (des.exists()) {
				des.delete();
			}
			Image image = javax.imageio.ImageIO.read(src);
			BufferedImage tag = new BufferedImage(this.width, this.height,
					BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(image, 0, 0, this.width, this.width,
					null); // 绘制缩小后的图
			Iterator it = ImageIO.getImageWritersBySuffix("jpg");
			if (it.hasNext()) {
				FileImageOutputStream fileImageOutputStream = new FileImageOutputStream(
						des);
				ImageWriter iw = (ImageWriter) it.next();
				ImageWriteParam iwp = iw.getDefaultWriteParam();
				iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
				iwp.setCompressionQuality(quality);
				iw.setOutput(fileImageOutputStream);
				iw.write(null, new IIOImage(tag, null, null), iwp);
				iw.dispose();
				fileImageOutputStream.flush();
				fileImageOutputStream.close();
			}
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {

		}

	}
}